'''
Created on 21 juil. 2010

@author: laurent
'''
import glob, mimetypes, socket, os

from SocketServer import BaseServer
from BaseHTTPServer import HTTPServer
from Multiplex import Multiplex

try:
    openssl_installed = False
    from OpenSSL import SSL
    openssl_installed = True
except ImportError:
    pass

class SecureHTTPServer(HTTPServer):
    def __init__(self, server_address, HandlerClass, cmd=None, env_term=None, ssl_enabled=True, ssl_cert=None, www_dir='www'):
        BaseServer.__init__(self, server_address, HandlerClass)
        # Setup SSL
        if ssl_enabled:
            try:
                ctx = SSL.Context(SSL.SSLv23_METHOD)
#                ctx.set_options(SSL.OP_NO_SSLv2)
                ctx.use_privatekey_file(ssl_cert)
                ctx.use_certificate_chain_file(ssl_cert)
                # Demand a certificate
#                ctx.set_verify(SSL.VERIFY_PEER|SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
#                    verify_cb)
#                ctx.load_verify_locations(os.path.join(dir, 'CA.cert'))
            except SSL.Error:
                self.socket = None
                return
        # Setup webshell multiplex
        self.webshell_files = {}
        for i in ['css', 'html', 'js', 'gif', 'jpg', 'png']:
            for j in glob.glob(www_dir + '/*.%s' % i):
                self.webshell_files[os.path.basename(j)] = file(j).read()
        self.webshell_mime = mimetypes.types_map.copy()
        self.webshell_multiplex = Multiplex(cmd, env_term)
        # Open socket
        self.socket = socket.socket(self.address_family, self.socket_type)
        if ssl_enabled:
            self.socket = SSL.Connection(ctx, self.socket)
        self.server_bind()
        self.server_activate()
    def stop(self):
        self.socket.close()
        self.webshell_multiplex.stop()
